package com.zxjbyte.yiyi.framework.mybatis.util;

import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.support.ColumnCache;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.zxjbyte.yiyi.framework.common.util.LambdaFieldUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @Author zhangxingjia
 * @Date 2023/3/15 11:52
 * @Version: 1.0
 */
public class MybatisUtil {

    /**
     * 将拦截器添加到MybatisPlusInterceptor中指定位置
     *
     * @param interceptor 链
     * @param inner 拦截器
     * @param index 位置
     */
    public static void addInterceptor(MybatisPlusInterceptor interceptor, InnerInterceptor inner, int index) {
        List<InnerInterceptor> inners = new ArrayList<>(interceptor.getInterceptors());
        inners.add(index, inner);
        interceptor.setInterceptors(inners);
    }

    /**
     * 获取数据库字段名
     *
     * @param func1 指定字段函数
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> String getColumnName(Function<T, ?> func1, Class<?> clazz){
        Map<String, ColumnCache> columnMap = LambdaUtils.getColumnMap(clazz);
        String fieldName = LambdaFieldUtil.getFieldName(func1);
        return columnMap.get(LambdaUtils.formatKey(fieldName)).getColumn();
    }
}
